package com.daydayup.learn;

import java.util.ArrayList;
import java.util.concurrent.*;

public class FutureDemo {
    public static void main(String[] args) {
        // 创建线程池
        ExecutorService service = Executors.newFixedThreadPool(10);
        // 提交任务,并用Futer接收返回结果
        ArrayList<Future<String>> allFuters = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            Future<String> future = service.submit(i < 2 ? new SlowTask() : new FastTask());
            allFuters.add(future);
        }
        for (int i = 3; i >= 0; i--) {
            Future<String> future = allFuters.get(i);
            String s;
            try {
                s = future.get();
                System.out.println(s);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        }
        service.shutdown();
    }
}

class SlowTask implements Callable<String> {

    @Override
    public String call() throws Exception {
        Thread.sleep(5000);
        return "速度慢的任务 -> " + System.currentTimeMillis();
    }
}

class FastTask implements Callable<String> {

    @Override
    public String call() throws Exception {
        return "速度快的任务 -> "+System.currentTimeMillis();
    }
}